package com.ding.common;


//心跳
public class Heartbeat {

    //当前时间
    private long time;

    //心跳检测超时
    private long heartbeatTimeout;

    //心跳周期
    private long cycle;

    //用于超时检测
    private Waiter.TaskHolder taskHolder;

    public  Heartbeat(long cycle, long heartbeatTimeout) {
        this.heartbeatTimeout = heartbeatTimeout;
        this.cycle = cycle;
    }

    public void updateTime() {
        time = System.currentTimeMillis();
    }

    public  void start() {
        updateTime();
        taskHolder = Waiter.setInterval(() -> {
            hearbeat();
        }, cycle);
    }

    public void clear() {
        if (this.taskHolder != null) {
            this.taskHolder.clear();
        }
    }

    protected void hearbeat() {
    }

    protected boolean isDeath() {
        return System.currentTimeMillis() - time > heartbeatTimeout;
    }

}
